package com.nb.service.impl;

import com.mybatisflex.core.query.QueryWrapper;
import com.nb.DTO.CaseDTO;
import com.nb.DTO.CaseQueryDTO;
import com.nb.DTO.CaseUpdateDTO;
import com.nb.VO.CaseDetailVO;
import com.nb.VO.CaseVO;
import com.nb.entity.Case;
import com.nb.entity.CaseMaterial;
import com.nb.entity.Lawyer;
import com.nb.entity.User;
import com.nb.mapper.CaseMapper;
import com.nb.mapper.CaseMaterialMapper;
import com.nb.mapper.LawyerMapper;
import com.nb.mapper.UserMapper;
import com.nb.service.CaseService;
import com.nb.utils.LocalFileStorage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class CaseServiceImpl implements CaseService {

    @Autowired
    private CaseMapper caseMapper;
    @Autowired
    private CaseMaterialMapper caseMaterialMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private LawyerMapper lawyerMapper;

    @Override
    @Transactional
    public void caseApplication(CaseDTO caseDTO) {

        Case caseEntity = new Case();
        caseEntity.setUserId(caseDTO.getUserId());
        caseEntity.setType(caseDTO.getType());
        caseEntity.setTitle(caseDTO.getDescription().substring(0, 10));
        caseEntity.setDescription(caseDTO.getDescription());
        caseEntity.setStatus("PENDING");
        //生成caseId，CASE开头，后面年、月、日、时
        caseEntity.setCaseNo("CASE" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));
        caseEntity.setApplyTime(LocalDateTime.now());
        caseMapper.insertSelective(caseEntity);
        // 保存案件材料
        MultipartFile[] files = caseDTO.getFiles();
        String[] uniqueFileNames = new String[files.length];
        try {
            for (int i = 0; i < files.length; i++) {
                uniqueFileNames[i] = LocalFileStorage.storeFile(files[i]);
                CaseMaterial caseMaterial = new CaseMaterial();
                caseMaterial.setCaseId(caseEntity.getId());
                caseMaterial.setMaterialType("OTHER");
                caseMaterial.setMaterialName(files[i].getOriginalFilename());
                caseMaterial.setStoragePath("/uploads/" + uniqueFileNames[i]);
                caseMaterial.setUploadTime(LocalDateTime.now());
                caseMaterialMapper.insertSelective(caseMaterial);
            }
        } catch (IOException e) {
            throw new RuntimeException("文件上传失败");
        }
    }

    @Override
    public List<CaseVO> caseList(CaseQueryDTO caseQueryDTO) {
        QueryWrapper queryWrapper = QueryWrapper.create();
        if (!Objects.equals(caseQueryDTO.getCaseName(), "")) {
            queryWrapper.like("title", caseQueryDTO.getCaseName());
        }
        if (!Objects.equals(caseQueryDTO.getCaseType(), "")) {
            queryWrapper.eq("type", caseQueryDTO.getCaseType());
        }
        if (!Objects.equals(caseQueryDTO.getStatus(), "")) {
            queryWrapper.eq("status", caseQueryDTO.getStatus());
        }
        List<Case> caseList = caseMapper.selectListByQuery(queryWrapper);
        List<CaseVO> caseVOList = new ArrayList<>();
        Long userId;
        for (Case caseEntity : caseList) {
            userId = caseEntity.getUserId();
            User user = userMapper.selectOneById(userId);
            CaseVO caseVO = new CaseVO();
            caseVO.setId(caseEntity.getId());
            caseVO.setCaseName(caseEntity.getTitle());
            caseVO.setCaseType(caseEntity.getType());
            caseVO.setApplicant(user.getUsername());
            caseVO.setStatus(caseEntity.getStatus());
            caseVO.setPhone(user.getPhone());
            caseVO.setLawyerId(caseEntity.getLawyerId());
            caseVOList.add(caseVO);
        }
        return caseVOList;
    }

    @Override
    public CaseDetailVO caseDetail(Long id) {
        Case caseEntity = caseMapper.selectOneById(id);
        Long userId = caseEntity.getUserId();
        User user = userMapper.selectOneById(userId);
        CaseDetailVO caseDetailVO = new CaseDetailVO();
        caseDetailVO.setId(caseEntity.getId());
        caseDetailVO.setLawyerId(caseEntity.getLawyerId());
        caseDetailVO.setCaseNo(caseEntity.getCaseNo());
        caseDetailVO.setCaseName(caseEntity.getTitle());
        caseDetailVO.setCaseType(caseEntity.getType());
        caseDetailVO.setStatus(caseEntity.getStatus());
        caseDetailVO.setApplicant(user.getUsername());
        caseDetailVO.setRealName(user.getRealName());
        caseDetailVO.setPhone(user.getPhone());
        caseDetailVO.setDescription(caseEntity.getDescription());
        caseDetailVO.setApplyTime(caseEntity.getApplyTime());
        caseDetailVO.setMaterials(caseMaterialMapper.selectListByQuery(QueryWrapper.create().eq("case_id", caseDetailVO.getId())));
        return caseDetailVO;
    }

    @Override
    public void caseUpdate(Long id, CaseUpdateDTO caseUpdateDTO) {
        Case caseEntity = new Case();
        caseEntity.setId(id);
        caseEntity.setStatus(caseUpdateDTO.getStatus());
        caseEntity.setType(caseUpdateDTO.getCaseType());
        caseEntity.setDescription(caseUpdateDTO.getDescription());
        caseEntity.setTitle(caseUpdateDTO.getCaseName());
        caseEntity.setLawyerId(caseUpdateDTO.getLawyerId());
        caseMapper.update(caseEntity);
    }
}
